package com.sunwayworld.dev.core.generate;

import java.io.File;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.sunwayworld.dev.core.valueobject.JspObject;
import com.sunwayworld.dev.io.freemarker.GenerateUtils;
import com.sunwayworld.dev.util.DevConfigUtil;
import com.sunwayworld.dev.util.StringDevUtil;

/**
 * 
 * @author sagitta
 * 
 */
public class GenerateJSP {
	private JspObject jspObject;

	private String baseWeb = "";;

	private String srcPath;

	private String vmPath;

	private Map context = new HashMap();

	public GenerateJSP(JspObject jspObject) {
		baseWeb = DevConfigUtil.getProperty("web");
		this.jspObject = jspObject;
		String srcPath = baseWeb + File.separator
				+ jspObject.getJspPath().replace('/', File.separatorChar);
		this.srcPath = srcPath;
		this.vmPath = jspObject.getVmPath();
		this.context = jspObject.getContext();
		init();
	}

	@SuppressWarnings("unchecked")
	private void init() {

		if (!context.containsKey("copyright")) {
			context.put("copyright", DevConfigUtil.getProperty("copyright"));
		}
		if (!context.containsKey("company")) {
			context.put("company", DevConfigUtil.getProperty("company"));
		}
		if (!context.containsKey("author")) {
			context.put("author", DevConfigUtil.getProperty("author"));
		}
		if (!context.containsKey("since")) {
			context.put("since", StringDevUtil.safeDate(new Date()));
		}
		if (!context.containsKey("title")) {
			context.put("title", "");
		}
		if (!context.containsKey("description")) {
			context.put("description", "");
		}
	}

	public void generateCode() {
		try {
			GenerateUtils gf = new GenerateUtils();

			copyProperties(jspObject, context);
			gf.generate(vmPath, srcPath, context);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@SuppressWarnings("unchecked")
	private void copyProperties(Object provide, Map context) {

		if (provide == null || context == null)
			return;
		Field[] fields = provide.getClass().getFields();
		for (int i = 0; i < fields.length; i++) {
			String fieldName = fields[i].getName();

			try {
				Object temp = fields[i].get(provide);
				if (temp != null) {
					context.put(fieldName, temp);
				}
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}
}
